<template>
    <div class="app-container">
        <div v-show="$route.path == '/corporateArchitecture'">
            <section>
                <div class="line-box-top">
                    <div class="chunk">
                        <div class="chunk-title"> 姓名：</div>
                        <el-input v-model="form.name" placeholder="搜索" style="width:100%" suffix-icon="el-icon-search" @keyup.enter.native="postStationUser(1)" @blur="postStationUser(1)"></el-input>
                    </div>
                    <div class="chunk ">
                        <div class="chunk-title">编号：</div>
                        <el-input v-model="form.number" placeholder="搜索" style="width:100%" suffix-icon="el-icon-search" @keyup.enter.native="postStationUser(1)" @blur="postStationUser(1)"></el-input>
                    </div>
                </div>
                <div class="mainBox dis_flex">
                    <div class="content_left">
                        <!-- <div class="topNav dis_flex items_center">
                            <el-input v-model="organ_name" placeholder="输入部门/岗位" style="width: 180px" clearable></el-input>
                            <span @click="postOrganLists" class="iconfont iconsearch search dis_block mr20"></span>
                        </div> -->
                        <el-tree ref="tree" :data="dataList" :props="defaultProps" @node-contextmenu="handleNodeClick" @node-click="handleNodeClick" >
                            <template slot-scope="{ node, data }">
                                <div @click="boxClick" class="select_icon">
                                    <!-- 图标 -->
                                    <span v-if="node.level == 1" class="el-icon-arrow-down"></span>
                                    <!-- <svg v-else-if="node.level == 2" class="icon" aria-hidden="true">
                                        <use xlink:href="#iconwenjian"></use>
                                    </svg>
                                    <svg  v-else-if="node.isLeaf" class="icon" aria-hidden="true">
                                        <use xlink:href="#iconlingdai"></use>
                                    </svg>
                                    <svg v-else-if="node.level == 3" class="icon" aria-hidden="true">
                                        <use xlink:href="#iconbianzu"></use>
                                    </svg> -->
                                    <span v-if="node.isLeaf" @click="searchAjob(data)" class="content_val">{{ data.name }}</span>
                                    <span v-else class="content_val">{{ data.name }}</span>

                                    <el-popover  placement="bottom" ref="popover" width="200" trigger="click" v-model="data.isShow">
                                        <div v-if="node.level == 1" class="" ref="boxChunk">
                                            <div class="zi_cont" @click="addLevel(data, 2)">
                                                新建下级部门
                                            </div>
                                            <!-- <div class="zi_cont" @click="setzuzhi(data)">
                                                编辑组织
                                            </div> -->
                                        </div>
                                        <!-- <div v-if="data.type != 1" class="" ref="boxChunk">
                                            <div class="zi_cont" @click="closeBumen(data)">
                                                删除岗位
                                            </div>
                                        </div> -->
                                        <div v-else class="" ref="boxChunk2">
                                            <div class="zi_cont" @click="addLevel(data, 2)">
                                                新建下级部门
                                            </div>
                                            <div class="zi_cont" @click="addLevel(data, 1)">
                                                新建平级部门
                                            </div>
                                            <div class="zi_cont" @click="clickBranch(data)">
                                                编辑部门
                                            </div>
                                            <div class="zi_cont" @click="closeBumen(data)">
                                                删除部门
                                            </div>
                                            <div class="zi_cont" @click="addLevel(data, 2, true)">
                                                新建岗位
                                            </div>
                                        </div>
                                        <span slot="reference" :fgs="data.$treeNodeId" class="el-icon-setting"></span>
                                    </el-popover>
                                    <span>({{data.user_count||0}})</span>
                                </div>
                            </template>
                        </el-tree>
                    </div>
                    <div class="content_right" v-loading="loading">
                        <el-table @row-click="(e) => handleClick(e.id)" :data="tableData" style="width: 100%" >
                            <el-table-column type="selection" align="center" width="45"></el-table-column>
                            <el-table-column prop="id" label="序号" align="center" width="80">
                            </el-table-column>
                            <el-table-column prop="username" label="姓名" align="center">
                            </el-table-column>
                            <el-table-column prop="number" label="工号" align="center">
                            </el-table-column>
                            <el-table-column prop="position.name" label="岗位" align="center">
                            </el-table-column>
                            <el-table-column prop="phone" label="手机号" align="center">
                            </el-table-column>
                            <el-table-column prop="email" label="邮箱" width="220" align="center">
                            </el-table-column>
                            <el-table-column prop="status" label="状态" align="center">
                                <template slot-scope="scope">
                                    {{ scope.row.status | staffStatus }}
                                </template>
                            </el-table-column>
                            <!-- <el-table-column label="操作" align="center">
                                <template slot-scope="scope">
                                    <span @click.stop="handleClick(scope.row.id, true)" style="cursor: pointer">修改</span>
                                </template>
                            </el-table-column> -->
                        </el-table>

                        <el-pagination style="margin-top: 40px;text-align: center;padding-bottom: 20px;" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page" :page-sizes="[10, 20, 50, 100]" :page-size="form.limit" layout="total, sizes, prev, pager, next, jumper" :total="form.total">
                    </el-pagination>
                    </div>
                </div>
            </section>
        </div>
        <!-- 部门操作 -->
        <el-dialog :title="dialogTitle" :visible.sync="isAddsection" width="600px" :before-close="branchClose">
            <div class="addsection">
                <div class="dialog_title">基本信息</div>
                <el-form label-position="left" :model="organNameForm" :rules="organNameRules" ref="organNameFormres1" label-width="130px" class="demo-ruleForm">
                    <el-form-item label="部门名称：" prop="name">
                        <el-input v-model="organNameForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="部门编号：" prop="number">
                        <el-input v-model="organNameForm.number"></el-input>
                    </el-form-item>
                    <el-form-item label="部门负责人：">
                        <el-input 
                        style="margin-right: 50px;"
                        v-model="organNameForm.leaderId" 
                        placeholder="请输入部门编号"></el-input>
                        <el-select
                            v-model="organNameForm.leader"
                            reserve-keyword
                            filterable
                            remote
                            placeholder="请输入员工姓名"
                            :remote-method="remoteMethod"
                            @change="choiceStaff"
                            :loading="staffLo">
                            <el-option v-for="item in principalList" :key="item.id" :label="item.username" :value="item.id"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="isAjob" label="上级部门：">
                        <el-input readonly v-model="organNameForm.superior"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div class="cf">
                <div class="floright">
                    <el-button @click="branchClose()">取 消</el-button>
                    <el-button :loading="loadingBtn" type="primary" @click="setBranch">确 定</el-button>
                </div>
            </div>
        </el-dialog>
        <!-- 岗位操作 -->
        <el-dialog :title="dialogTitle" :visible.sync="isAddpost" width="600px" :before-close="branchClose"> 
            <div style="" class="addsection">
                <div class="dialog_title">基本信息</div>
                <el-form label-position="left" :model="post" :rules="postRules" ref="organNameFormres2" label-width="130px" class="demo-ruleForm">
                    <el-form-item label="部门名称：" prop="department_id">
                        <el-cascader 
                        v-model="post.department_id" 
                        placeholder="搜索" 
                        :options="dataList" 
                        filterable 
                        style="width:100%"
                        expand-trigger="hover" 
                        :props="{children:'child',label:'name',value:'id',checkStrictly: true}"
                        clearable>
                            
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="岗位名称：" prop="name">
                        <el-input v-model="post.name"></el-input>
                    </el-form-item>
                    <el-form-item label="岗位标识：" prop="info">
                        <el-input type="textarea" v-model="post.info"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div class="cf">
                <div class="floright">
                    <el-button @click="branchClose()">取 消</el-button>
                    <el-button :loading="loadingBtn" type="primary" @click="setPosition">确 定</el-button>
                </div>
            </div>
        </el-dialog>
        <router-view></router-view>
    </div>
</template>

<script>
// const axios = require('axios');
// import exportExcel from "@/utils/export";
export default {
    data() {
        return {
            isFirst: true,
            isAjob: false,
            loadingBtn: false, //按钮是否加载
            loading: false, //表格加载
            loading2: false, //部门列表加载
            isAddpost: false, //岗位页
            isAddsection: false, //部门页
            isSetsection: false, //顶级部门页
            dialogTitle: "", //标题
            visible: false, //岗位页
            principalList: [], //负责人
            //
            organ_name: null, //部门/岗位
            form: {
                name: null, //姓名/手机号
                number: null, //编号：
                limit: 10, //条数
                page: 1, //第几页
                total: 0, //总数
            },
            post:{
                department_id:0,//部门id
                name:'',//岗位名称
                info:'',//岗位标识
            },
            organNameForm: {
                pid:0,  //上级部门id
                name: "", //部门名称
                leaderId:'',//部门负责人编号
                leader:'',//部门负责人
                sort: "", //排序
                leval:0,//部门等级 顶级部门是1级
                number: "", //部门编号
            },
            postRules:{
                department_id:[{type: 'array', required: true, message: '请选择部门', trigger: 'change' }],
                name: [{ required: true, message: "请输入岗位名称", trigger: 'blur' }],
                info: [{ required: true, message: "请输入岗位标识", trigger: 'blur' }],
            },
            organNameRules: {
                name: { required: true, message: "请输入部门名称", trigger: 'blur' },
                number: [{ required: true, message: "请输入部门编号", trigger: 'blur' }],
                leader: [
                    { required: true, message: "请选择部门负责人", trigger: "change" },
                ],
            },
            statusList: ["试用期", "在岗", "休假", "离职"],
            tableData: [],
            dataList: [], //部门列表
            staffLo:false,//员工搜索显示
            defaultProps: {
                //部门列表对应字段
                children: "child",
                label: "name",
            },
        };
    },
    watch: {
        isAddsection(val){
            if(!val){
                this.organNameForm.name = ""
                this.organNameForm.code = ""
                this.organNameForm.member_id = ""
                this.organNameForm.superior = ""
            }
        }
    },
    created() {
        if(this.$route.params.page){
            this.form.page = Number(this.$route.params.page)
        }
        this.postStationUser();
        this.postOrganLists();
        // this.postMemberlists();
    },
    filters: {
        staffStatus(val) {
            switch (val) {
                case 0:
                    val = "离职";
                    break;
                case 1:
                    val = "在职";
                    break;
            }
            return val;
        },
    },
    methods: {
        
        choiceStaff(val){//选择员工
            val = this.principalList[this.principalList.findIndex(v=>v.id==val)].number;
            console.log(val);
            this.organNameForm.leaderId = val;
        },
        async remoteMethod(query){//员工搜索
            if (query !== '') {
                this.staffLo = true;
                let {code,data} = await this.$Http.getUser({
                    name:query
                })
                if(code){
                    this.staffLo = false;
                    this.principalList = data.data;
                }
            } else {
                this.principalList = [];
            }
        },
        processListExport(){
            axios({
                method: 'post',
                // url: 'http://oa.showonderkj.com/api/member/getStationUserExport',
                url: this.$baseUrl+'/member/getStationUserExport',
                params: this.form,
                responseType: 'blob',
                headers:{
                    'token':localStorage.getItem('token')
                }
            }).then(res=>{
                let data = res.data;
                let fileReader = new FileReader();
                fileReader.onload = () => {
                try {
                    let jsonData = JSON.parse(this.result);
                        if (jsonData.code) {
                            // 说明是普通对象数据，后台转换失败
                            // to do something
                            this.$message.error(jsonData.msg)
                        }
                    } catch (err) {
                        // 解析成对象失败，说明是正常的文件流
                        this.downLoadXls(res.data,'公司组织架构.xls')
                    }
                };
                fileReader.readAsText(data)
            })
        },
        downLoadXls(data, filename) {
                //var blob = new Blob([data], {type: 'application/vnd.ms-excel'})接收的是blob，若接收的是文件流，需要转化一下
            if (typeof window.chrome !== 'undefined') {
                // Chrome version
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(data);
                link.download = filename;
                link.click();
            } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE version
                var blob = new Blob([data], { type: 'application/force-download' });
                window.navigator.msSaveBlob(blob, filename);
            } else {
                // Firefox version
                var file = new File([data], filename, { type: 'application/force-download' });
                window.open(URL.createObjectURL(file));
            }
        },
        exportExcel() {
            let val = this.tableData;
            let keyLisst = [];
            for (let item in val) {
                keyLisst.push({
                    '序号': val[item].id,
                    '姓名': val[item].name,
                    '部门': val[item].organName,
                    '岗位': val[item].stationName,
                    '手机号': val[item].phone,
                    '状态': val[item].station_status,
                });
            }
            // exportExcel.exportExcel(keyLisst, this.$route.meta.title);
        },
        searchAjob(data) {
            //
            // this.form.id = data.id;
            console.log(data.id, "id");
            // this.postStationUser();
        },
        addLevel(data, level, isto) {
            console.log(data, level, isto);
            //添加平级/下级部门
            if (isto) {
                this.dialogTitle = `新建岗位/${data.name}`;
               
                // this.organNameForm.type = 2;
                this.isAddpost = true;
                this.organNameRules.name.message = "请输入岗位";
            } else {
                this.isAddsection = true;
                // this.organNameForm.type = 1;
                this.dialogTitle = "添加部门";
            }
            // data.isShow = false;
            if (level == 1) {
                //平级
                 this.isAjob = true;
                this.organNameForm.pid = data.pid;
                this.organNameForm.superior = data.superior;
                // this.organNameForm.superior = data.superior;
                this.organNameForm.level = data.level;
            } else if (level == 2) {
                //下级
                if(isto){
                    console.log(data,"@@@@");
                    this.post.department_id = data.department_id;
                }else{
                    this.organNameForm.pid = data.id;
                    this.organNameForm.level = data.level + 1;
                    // this.organNameForm.superior = data.name;
                }
            }
        },
        setBranch() {
            //添加部门/修改部门
            this.$refs.organNameFormres1.validate(async (valid) => {
                if (!valid) return;
                    let {} = this.organNameForm;
                    this.loadingBtn = true;
                    let {code,data} = await this.$Http.setDepartment(this.organNameForm);
                    this.loadingBtn = false;
                    if(code){
                        this.$message({ type: "success", message: "添加成功!" });
                        this.isAddsection = false;
                        this.isAddpost = false;
                        this.postOrganLists();
                    }
                // if (this.organNameForm.id){
                //      this.postOrganUpdate();
                // } else {
                //     this.postOrganAdd();
                // }
            });
        },
        setPosition(){//添加岗位
            this.$refs.organNameFormres2.validate(async (valid) => {
                if(!valid)return;
                    let {department_id} = this.post;
                    this.post.department_id = department_id[department_id.length-1];
                    this.loadingBtn=true;
                    let {code,data} = await this.$Http.setPosition(this.post);
                    this.loadingBtn = false;
                    if(code){
                        this.$message({ type: "success", message: "添加成功!" });
                        this.isAddsection = false;
                        this.isAddpost = false;
                        this.$refs.post.resetFields();
                        this.branchClose();
                        this.postOrganLists();
                    }
            });
        },
        async postOrganAdd() {
            //添加部门
            try {
                this.loadingBtn = true;
                let { data, code } = await this.$api.postOrganAdd(this.organNameForm);
                if (code == 200) {
                    this.$message({ type: "success", message: "添加成功!" });
                    this.isAddsection = false;
                    this.isAddpost = false;
                    this.$refs.organNameFormres1.resetFields();
                    this.postOrganLists();
                }
                this.loadingBtn = false;
            } catch (error) {
                this.loadingBtn = false;
            }
        },
        setzuzhi(data) {
            //编辑组织
            this.isSetsection = true;
            this.dialogTitle = `编辑部门/${data.name}`;
            this.organNameForm = Object.assign({}, data);
        },
        async postMemberlists() {
            //获取部门负责人
            let { data } = await this.$api.postMemberlists();
            this.principalList = data;
        },
        async postOrganUpdate() {
            //编辑部门
            try {
                this.loadingBtn = true;
                let { data, code } = await this.$api.postOrganUpdate(this.organNameForm);
                if (code == 200) {
                    this.isSetsection = false;
                    this.isAddsection = false;
                    this.$message({ type: "success", message: "修改成功!" });
                    this.organNameForm.id = null
                    this.postOrganLists();
                }
                this.loadingBtn = false;
            } catch (error) {
                this.loadingBtn = false;
            }
        },
        async postOrganLists() {
            //获取部门
            this.loading2 = true;
            let { data,code } = await this.$Http.getDepartment({ name: this.organ_name });
            if(code){
                this.dataList = this.closeData(data, -1);
                console.log(this.dataList,"QWERTYU");
            }
            this.loading2 = false;
        },
        reset() {
            //重置搜索
            console.log(this.$options.data().form);
            this.$data.form = Object.assign({}, this.$options.data().form);
            this.postStationUser();
        },
        async postStationUser(sou) {
            //获取组织架构用户列表
            try {
                 if(sou){
                    this.form.page = 1;
                }
                this.loading = true;
                let requestData = this.form;
                let { data,code } = await this.$Http.getUser(requestData);
                console.log(data,"用户");
                if(code){
                    this.isFirst = false
                    this.tableData = data.data;
                    this.form.limit = data.per_page;
                    this.form.total = data.total;
                }
                this.loading = false;
            } catch (error) {
                this.loading = false;
            }
        },
        clickBranch(data) {
            //编辑部门点击
            this.isAddsection = true;
            this.dialogTitle = `编辑部门/${data.name}`;
            console.log(data,"data");
            this.organNameForm = Object.assign({}, data);
        },
        closeBumen(data) {
            //删除部门
            data.isShow = false;
            this.$confirm("确定要删除该部门信息吗？ 删除后不可恢复！", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    this.$Http
                        .delDepartment({ id: data.id })
                        .then((res) => {
                            if (res.code) {
                                this.$message({ type: "success", message: "删除成功!" });
                                this.postOrganLists();
                            }
                        })
                        .catch(() => { });
                })
                .catch(() => {
                    // this.$message({ type: 'info', message: '已取消删除' });
                });
        },
        zationClose(done) {
            //组织关闭回调
            this.$refs.organNameFormres1.resetFields();
            done();
        },
        branchClose(done) {
            //部门关闭回调
            this.isAddsection = false;
            this.isAddpost = false;
            this.isAjob = false;
            this.organNameForm = this.$options.data().organNameForm;
            // this.organNameRules = this.$options.data().organNameRules;
            this.post =  this.$options.data().post;
            // this.postRules = this.$options.data().postRules;
            if(this.$refs.organNameFormres1)
                this.$refs.organNameFormres1.resetFields();
            if(this.$refs.organNameFormres2)
                this.$refs.organNameFormres2.resetFields();
            if(done) done();
        },
        closeData(list, id, superior,ids) {
            return list.map(v=>{
                    if (id != v.$treeNodeId)v.isShow = false;
                        v.superior = superior;
                    ids?v.department_id = [...ids,v.id]:v.department_id=[v.id]
                    
                    if(v.child&&v.child.length)
                        v.child = this.closeData(v.child,id,v.name,v.department_id)
                    else delete v.child
                return v;
            })
        },
        boxClick(e) {
            // console.log("@@",e.target.attributes.fgs.value)
            if (e.target.attributes.fgs) {
                e.stopPropagation();
                this.closeData(this.dataList, e.target.attributes.fgs.value);
            } else this.closeData(this.dataList);
        },
        handleChange(e) {
            console.log(e, ".JPG");
        },
        handleClick(id, top) {
            //修改
            // this.$router.push({
            //     path: "/systemManagement/companyBuild/companyBuildDetails",
            //     query: { id, type: top ? 1 : 0, page: this.form.page },
            // });
        },
        handleNodeClick(e, e2) {
            console.log(e);
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.form.limit = val;
            this.postStationUser();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.form.page = val;
            this.postStationUser();
        },
    },
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item .el-form-item__content{
    display: flex;
}
.floright{
    display: flex;
    justify-content: center;
    margin-top: 50px;
}
.app-container {
    background: #eee;
    padding: 30px;
    height: 100%;
    .kong {
        height: 40px;
    }
    section {
        background: #fff;
        border-radius: 16px;
        // padding-top: 18px;
        padding: 20px 0;
    }
}
.iconsearch {
    cursor: pointer;
}
.mainBox {
    padding: 30px;
    box-sizing: border-box;
    .content_left {
        margin-right: 20px;
        // min-width: 240px;
    }
    .content_right {
        // flex: 1;
        width: calc(100% - 250px);
    }
    .topNav {
        margin-bottom: 30px;
    }
}
.dialog_title {
    font-size: 20px;
    font-weight: 400;
    color: #333333;
    line-height: 28px;
    margin-bottom: 40px;
}
.addsection {
    ::v-deep.el-form-item__content {
        width: 350px;
    }
    ::v-deep .el-dialog__body {
        padding: 30px 50px 30px 100px;
    }
}
.zi_cont {
    margin: 5px 0;
    padding: 5px;
    cursor: pointer;
    &:hover {
        background: #f5f7fa;
    }
}
.select_icon {
    display: flex;
    .content_val {
        margin: 0 5px;
    }
}

.content {
    background: #fff;
    // padding: 42px 12px;

    ::v-deep.el-tree-node__expand-icon {
        display: none;
    }
    ::v-deep.el-tree-node:focus > .el-tree-node__content {
        background: #4a90e2;
        color: #fff;
    }
    .search {
        width: 43px;
        height: 40px;
        border: 1px solid #dcdfe6;
        text-align: center;
        line-height: 40px;
        color: #b5b6b8;
        font-size: 21px;
    }
    .btn {
        width: 100px;
        height: 40px;
        border-radius: 4px;
        font-size: 14px;
        text-align: center;
        line-height: 40px;
        box-sizing: border-box;
        cursor: pointer;
    }
    .btnSearch {
        background: #4a90e2;
        color: #ffffff;
    }
    .btnReset {
        background: #ffffff;
        border: 1px solid #4a90e2;
        color: #4a90e2;
    }
    .btnImport {
        background: #fafafa;
        border: 1px solid #dddddd;
        color: #333333;
    }
    .pagination {
        text-align: right;
        margin-top: 94px;
    }
    .mr20 {
        margin-right: 10px;
    }
}
</style>
<style lang="scss" scoped>
.content {
    ::v-deep.el-input__inner {
        border-radius: 0;
    }
}
</style>
